<template>
    <div class="workOrder">
        <div class="tabHeader">
            <el-tabs v-model="editableTabsValue" @tab-click="handleTabClick">
                <el-tab-pane v-for="(item,index) in editableTabs" :key="item.id" :name="item.name" :label="item.name">
                    <span slot="label">
                        <el-popover placement="bottom-start"
                            popper-class='custom'>
                            <span slot="reference" style="display:inline-block">{{item.name}}</span>
                            <div class="secondGroup">
                                <div class="item-card" v-for="(i,index) in secondGroupInfo.typeCountData" 
                                    :key="i.optionValue" 
                                    :class="{active:activeValue === i.optionValue}"
                                    @click="handleSecondGroup(i,secondGroupInfo,item)">
                                    <i class="iconfont icon-caiyouduo_hemaixiangqing-fanganxiangqing icon" style="font-size:18px"></i>
                                    <span class="groupName">{{i.optionName}}</span>
                                    <span class="groupName" style="margin-left:8px">{{i.optionNum}}</span>
                                </div>
                            </div>
                        </el-popover>
                    </span>
                </el-tab-pane>
            </el-tabs>
            <div class="setBtn">
                <my-button type='primary' plain size='mini' class='el-icon-circle-check'
                    @btnClick='$refs.saveScheme.showDialog()'>
                    保存当前
                </my-button>
                <my-button type='primary' size='mini' class='el-icon-edit-outline'
                    @btnClick='$refs.scheme.drawerOpen()'>
                    筛选方案
                </my-button>
            </div>
        </div>

        <!-- 动态表单 -->
        <dynamic-form :formDataList='formDataList' @getFormData='getFormData' ref='dynamicForm'></dynamic-form>

        <!-- 按钮操作 -->
        <custom-setbtn>
            <template #l_btn>
                <div class="l_btn">
                    <el-button type="primary" size="mini" icon="el-icon-circle-plus-outline"
                        @click="$router.push('/productionManagement/createOrder')" v-hasPermis="'button.createOrder'">创建工单</el-button>
                    <el-dropdown trigger="click">
                        <el-button type="primary" size="mini" icon="el-icon-s-operation" :disabled='isBatchCheck'
                            style='margin:0 10px'>批量操作
                        </el-button>
                        <el-dropdown-menu slot="dropdown">
                            <el-dropdown-item>
                                <el-button type="text" size="mini" icon="el-icon-video-play"
                                    @click="wosHandle('begin')" v-hasPermis="'button.batchStart'">批量开始</el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button type="text" size="mini" icon="el-icon-back" @click="wosHandle('suspend')"
                                    v-hasPermis="'button.batchRecall'">批量撤回</el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button type="text" size="mini" icon="el-icon-switch-button" v-hasPermis="'button.batchEnd'"
                                    @click="wosHandle('stop')">批量结束</el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button type="text" size="mini" icon="el-icon-circle-close" v-hasPermis="'button.batchCancel'"
                                    @click="wosHandle('cancel')">批量取消</el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button type="text" size="mini" icon="el-icon-printer"
                                    @click="batchPrint" v-hasPermis="'button.batchPrint'">批量打印</el-button>
                            </el-dropdown-item>
                            <el-dropdown-item>
                                <el-button type="text" size="mini" icon="el-icon-delete" @click="wosHandle('del')" 
                                    v-hasPermis="'button.batchDelete'"
                                >批量删除
                                </el-button>
                            </el-dropdown-item>
                            <el-dropdown-item class='urgent'>
                                <el-button type="text" size="mini" icon="iconfont icon-yangpinjiaji"
                                    @click="wosUrgent"
                                >批量加急
                                </el-button>
                            </el-dropdown-item>
                        </el-dropdown-menu>
                    </el-dropdown>
                    <my-button type="primary" size="mini" icon="el-icon-upload2" plain
                        @btnClick='getWorkOrderExport' :disabled='computedTotal'
                        v-hasPermis="'button.export'"
                        >
                        导出
                    </my-button>
                    <el-button type="primary" size="mini" icon="el-icon-download" plain
                        @click="openDialog('importMould')" v-hasPermis="'button.import'">导入</el-button>
                    <!-- 排序 -->
                    <sortList :tableTotal="tableTotal" @getSortInfoList="getSortInfoList" @isCacheSort="isCacheSort"></sortList>
                    <el-button type="text" size="mini" icon="el-icon-document"
                        @click="$router.push('/productionManagement/workOrder/loadLog')">查看导入日志</el-button>
                    <my-button type="text" size="mini" icon="el-icon-edit-outline"
                        @btnClick="openDialog('editMould')" v-hasPermis="'button.editPrintMould'">
                        编辑打印模版
                    </my-button>
                    <el-button type="text" size="mini" icon="el-icon-edit"
                        @click="$router.push('/productionManagement/workOrder/customEvent')">自定义事件</el-button>
                </div>
            </template>
            <template #r_btn>
                <div class="r_btn">
                    <my-button type="text" size="mini" icon="el-icon-time" @btnClick="$refs.records.open()">
                        操作记录
                    </my-button>
                    <my-button type="primary" size="mini" icon="el-icon-setting" @btnClick="cardHandle('workOrder')"
                        v-hasPermis="'button.cardSet'"
                    >
                        移动端卡片设置
                    </my-button>
                    <!-- 列配置表格 -->
                    <pop-checkbox :disposeGroup='disposeGroup' @handleChangeDiposeGroup='handleChangeDiposeGroup'></pop-checkbox>
                </div>
            </template>
        </custom-setbtn>

        <!-- 导入 -->
        <import-mould title='工单' ref='importMould' @importSuccess='importSuccess'></import-mould>

        <!-- 编辑打印模版 -->
        <common-dialog ref='editMould' :width="600" @getTemplate='getTemplate' @handleClose='fileList = []'>
            <template #title>
                <span class="title" style='color: rgba(0,0,0,.85);font-weight: 500;font-size: 14px;'>编辑打印模版</span>
            </template>
            <template #body>
                <div class='describe'>
                    可通过下载系统模版
                    <el-button type="text" size="mini" v-for="(i,index) in mouldTableData.slice(0,3)" :key='i.id'
                        @click="getDownloadTemplate({id:i.id},i.templateName)">
                        {{i.templateName}}
                        <span v-show='index < 2'>，</span>
                    </el-button>
                    <br />
                    根据业务需要编辑、上传新的模版。
                </div>
                <el-table :data="mouldTableData" border style="width: 100%" max-height="180"
                    :header-cell-style="{background:'#fafafa',color:'#000',fontWeight:400,fontSize:'12px'}"
                    :cell-style="{color:'#5a5a5a',fontSize:'12px',fontWeight:400}" v-loading="mouldLoading"
                    element-loading-background="rgba(250, 250, 250, 0.5)" element-loading-spinner="el-icon-loading">
                    <el-table-column label="模版">
                        <template slot-scope="scope">
                            <div class='mouldTableData'>
                                <div class='l_mould'>
                                    <span>{{scope.row.templateName}}</span>
                                    <span v-show='!scope.row.templateType'>系统模版</span>
                                </div>
                                <div class='r_mould'>
                                    <el-button type="text" size="mini"
                                        @click="getDeleteTemplate(scope.row.id)" v-show='scope.row.templateType'>删除</el-button>
                                    <el-button type="text" size="mini"
                                        @click="getDownloadTemplate({id:scope.row.id},scope.row.templateName)">下载</el-button>
                                </div>
                            </div>
                        </template>
                    </el-table-column>
                </el-table>
                <div class='upload'>
                    <el-upload :action="$global.uploadUrl+'/sys/printTemplate/uploadTemplate'" :file-list='fileList'
                        :headers='computedToken' :data='{belongModule:0}' :show-file-list='false'
                        :on-success='fileSuccess' accept='.xlsx,.xls' :disabled='mouldTableData.length >= 13'>
                        <el-button size="mini" type="primary" icon='el-icon-upload2' :disabled='mouldTableData.length >= 13'>上传模版</el-button>
                        <span slot="tip" style='margin-left:12px;color:rgb(155, 155, 155)'
                            class='el-icon-warning-outline'>最多上传10个，文件大小不超过1M，格式为.xlsx、.xls</span>
                    </el-upload>
                </div>
            </template>
            <template #footer>
                <span style='width:100%;text-align:center;display:inline-block'>
                    <el-button size="small" @click='$refs.editMould.closeDialog()' style='padding:7px 35px'>完 成</el-button>
                </span>
            </template>
        </common-dialog>

        <!-- 打印 -->
        <common-dialog ref='print' :width="550" @handleClose='excelRadio = 0'>
            <template #title>
                <span class="title">选择模版</span>
            </template>
            <template #body>
                <div class='dialogBody' style='padding:20px 15px'>
                    <p class='excel'>Excel模版打印</p>
                    <el-radio-group v-model="excelRadio">
                        <el-radio v-for="(i,index) in mouldTableData" :key='i.id' :label="index">
                            {{i.templateName}}
                            <span class='mould' v-show='!i.templateType'>系统模版</span>
                        </el-radio>
                    </el-radio-group>
                    <span class='printDown'>
                        <el-button type='primary' size="small" @click='excelPrintDown' style='padding:7px 35px'>下载打印</el-button>
                    </span>
                </div>
            </template>
        </common-dialog>

        <!-- 操作记录 -->
        <records ref="records"></records>

        <!-- 移动端卡片设置 -->
        <el-drawer title="卡片设置" :visible.sync="cardSetDrawer" direction="rtl" size='450px' custom-class='card'
            @close='cardSetClose'>
            <div class='cardSet' v-loading="cardSetLoading" element-loading-text="加载中" 
                element-loading-background="rgba(250, 250, 250, 0.5)" element-loading-spinner="el-icon-loading">
               <el-form :model="cardSetForm" :rules="cardSetRules" ref="cardSetForm" label-width="100px" size="mini"
                >
                    <el-form-item label="标题" prop="titleValues" placeholder='请选择'>
                        <el-select v-model="cardSetForm.titleValues" multiple filterable>
                            <el-option
                                v-for="(item,index) in titleValuesOptions"
                                :key="index"
                                :label="item.cnName"
                                :value="item.cnName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="封面" prop='coverValue'>
                        <el-select v-model="cardSetForm.coverValue" filterable>
                            <el-option
                                v-for="(item,index) in coverValueOptions"
                                :key="index"
                                :label="item.cnName"
                                :value="item.cnName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="展示字段" prop="columnValues" placeholder='请选择' style='overflow:hidden'>
                        <el-select v-model="cardSetForm.columnValues" multiple filterable @change='fieldChange'>
                            <el-option
                                v-for="(item,index) in columnValuesOptions"
                                :key="index"
                                :label="item.cnName"
                                :value="item.cnName">
                            </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item>
                        <div class='checkBox'>
                            <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
                            <el-checkbox-group v-model="checkedField" @change="handleCheckedCitiesChange">
                                <div v-for="(i,index) in fields" :key="index" class="group_div">
                                    <el-checkbox :label="i" style="width:100%"></el-checkbox>
                                    <!-- <span class="iconfont icon-row key"></span> -->
                                </div>
                            </el-checkbox-group>
                        </div>
                    </el-form-item>
                </el-form>
            </div>
            <div class="operate" style="textAlign:center">
                <el-button size="mini" style="padding:7px 35px" @click='cardSetDrawer = false'>取 消</el-button>
                <el-button type="primary" size="mini"style="padding:7px 35px" @click='saveCardSet({belongModule:0})'>确 定</el-button>
            </div>
        </el-drawer>

        <!-- 表格 -->
        <table-list :tableGroup='tableGroup' @getCheckedId='getCheckedId'
            :searchForm='searchForm' @getPrint='getPrint' @getTotal='getTotal' 
            @getSecondGroupInfo="getSecondGroupInfo" ref='tableList'>
        </table-list>

        <!-- 保存当前 -->
        <save-current ref="saveScheme" @getList='getList' :editableTabs='allTabs' @fromOutDrawerClose='fromOutDrawerClose'></save-current>

        <!-- 筛选方案--创建方案 -->
        <operate-scheme ref="scheme" :editableTabs='allTabs' @getList='getList' @fromOutDrawerClose='fromOutDrawerClose'
            @lastData='lastData'></operate-scheme>
    </div>
</template>

<script>
    import {
        screenPlanList,
        printTemplate,
        deleteTemplate,
        downloadTemplate,
        getSearchCache,
        setSearchCache
    } from '@/api/produceController'
    import {
        productColumns
    } from '@/api/customFieldController'
    import {h5CardSet} from "@/mixin"
    import request from '@/utils/request'
    import fileDownload from "js-file-download";
    import saveCurrent from './saveCurrent.vue'
    import operateScheme from './operateScheme.vue'
    import tableList from './tableList.vue'
    import dynamicForm from '@/components/dynamicForm'
    import commonDialog from './dialog.vue'
    import records from './records.vue'
    import sortList from './sortList.vue'
    export default {
        data() {
            return {
                editableTabsValue: '',
                editableTabs: [],
                allTabs:[],
                fromSavaCurrent:0,
                isMounted:'',
                secondGroupInfo:[],
                activeValue:'all',
                enumState:{
                    0:'未开始',
                    1:'执行中',
                    2:'已结束',
                    3:'已取消'
                },
                enumDynamicType:{
                    1:'今天',
                    2:'昨天',
                    3:'本周',
                    4:'上周',
                    5:'本月',
                    6:'上月',
                    7:'近三月',
                },
                customFieldMap:{},
                isCollapse: false,
                formDataList: {
                    formGroup: [{
                            label: 'code',
                            name: '工单编号',
                            prop: '',
                            placeholder: '请输入工单编号',
                            key: 'srk'
                        },
                        {
                            label: 'productCode',
                            name: '产品编号',
                            prop: '',
                            placeholder: '请输入产品编号',
                            key: 'srk',
                        },
                        {
                            label: 'productName',
                            name: '产品名称',
                            prop: '',
                            placeholder: '请输入产品名称',
                            key: 'srk'
                        },
                        {
                            label: 'productSpecification',
                            name: '产品规格',
                            prop: '',
                            placeholder: '请输入产品规格',
                            key: 'srk'
                        },
                        {
                            label: 'unit',
                            name: '产品单位',
                            prop: '',
                            placeholder: '请选择',
                            key: 'sci',
                            dataUrl: {
                                url: '/base/unit_other',
                                value: 'id'
                            }
                        },
                        {
                            label: 'comment',
                            name: '备注',
                            prop: '',
                            placeholder: '请填写',
                            key: 'srk'
                        },
                        {
                            label: ['planedNumberDown', 'planedNumberUp'],
                            name: '计划数',
                            prop: '',
                            key: 'jsk'
                        },
                        {
                            label: ['actualNumberDown', 'actualNumberUp'],
                            name: '实际数',
                            prop: '',
                            key: 'jsk'
                        },
                        {
                            label: ['goodProductNumberDown', 'goodProductNumberUp'],
                            name: '良品数',
                            prop: '',
                            key: 'jsk'
                        },
                        {
                            label: ['badProductNumberDown', 'badProductNumberUp'],
                            name: '不良品数',
                            prop: '',
                            key: 'jsk'
                        },
                        {
                            label: ['startTimeStart', 'startTimeEnd'],
                            name: '计划开始时间',
                            prop: '',
                            key: 'cki'
                        },
                        {
                            label: ['endTimeStart', 'endTimeEnd'],
                            name: '计划结束时间',
                            prop: '',
                            key: 'cki'
                        },
                        {
                            label: ['actualStartTimeStart', 'actualStartTimeEnd'],
                            name: '实际开始时间',
                            prop: '',
                            key: 'dpi'
                        },
                        {
                            label: ['actualEndTimeStart', 'actualEndTimeEnd'],
                            name: '实际结束时间',
                            prop: '',
                            key: 'dpi'
                        },
                        {
                            label: 'state',
                            name: '状态',
                            prop: '',
                            placeholder: '请选择',
                            key: 'sel',
                            cache:'cacheState',
                            node: {
                                default: [],
                                isRadio: false,
                                options: [{
                                        value: 0,
                                        label: '未开始'
                                    },
                                    {
                                        value: 1,
                                        label: '执行中'
                                    },
                                    {
                                        value: 2,
                                        label: '已结束'
                                    },
                                    {
                                        value: 3,
                                        label: '已取消'
                                    }
                                ]
                            }
                        },
                    ],
                    searchForm: {
                        code: '',
                        productCode: '',
                        productName: '',
                        productSpecification: '',
                        unit: '',
                        comment: '',
                        planedNumberDown: '',
                        planedNumberUp: '',
                        actualNumberDown: '',
                        actualNumberUp: '',
                        goodProductNumberDown: '',
                        goodProductNumberUp: '',
                        badProductNumberDown: '',
                        badProductNumberUp: '',
                        startTimeStart: '',
                        startTimeEnd: '',
                        endTimeStart: '',
                        endTimeEnd: '',
                        actualStartTimeStart: '',
                        actualStartTimeEnd: '',
                        actualEndTimeStart: '',
                        actualEndTimeEnd: '',
                        state: []
                    },
                    formSet: true,
                    type:'workOrder'
                },
                searchForm:{
                    customFieldMap:{},
                    searchOther:{},
                    page:1,
                    limit:10
                },
                mouldLoading: false,
                mouldTableData: [],
                tableTotal:0,
                ids: '',
                fileList:[],
                excelRadio: 0,
                disposeGroup: [],
                tableGroup:[],
                pieceOrBatch:'',
                cacheSortFlag:false,
                sortInfoList:[]
            }
        },
        components: {
            saveCurrent,
            operateScheme,
            dynamicForm,
            tableList,
            commonDialog,
            records,
            sortList
        },
        mixins:[h5CardSet],
        mounted(){
            if (this.$store.state.router === this.$route.path) {
                this.searchForm.page = this.$store.state.page || 1;
            }
            this.isMounted = 'mounted'
            this.getProductColumns({
                type: 'workOrder'
            })
            this.getSearchCacheFn({cacheName:'workOrder:workOrderList'}).then(()=>{
                this.getScreenPlanList({type:0})
            })
        },
        computed:{
            computedToken(){
                return {Authorization:localStorage.getItem('token')}
            },
            isBatchCheck(){
                return this.ids.length <= 0
            },
            computedTotal(){
                return this.tableTotal <= 0
            }
        },
        watch:{
            tableTotal(total){
                //当表格数据为空时 列配置和表头无自定义字段信息
                if(total <= 0) {
                    this.tableGroup = this.utils.filterCustomFields(this.tableGroup)
                    this.disposeGroup = this.utils.filterCustomFields(this.disposeGroup)
                }
            }
        },
        methods: {
            getProductColumns: async function(data){
                const res = await productColumns(data)
                if (res.code == 200) {
                    this.disposeGroup = []
                    this.tableGroup = []
                    res.data.map((item, i) => {
                        const key = {
                            index:'80',
                            code:'155',
                            list:'640',
                            name:'220',
                            productName:'130',
                            productSpecification:'70',
                            productCode:'150',
                            unit:'60',
                            state:'80',
                            startTime:'150',
                            endTime:'150',
                            reportedHours:'100',
                            planedNumber:'65',
                            actualNumber:'65',
                            goodProductNumber:'65',
                            badProductNumber:'70',
                            createName:'60',
                            editName:'60',
                            actualStartTime:'145',
                            actualEndTime:'145',
                            createTime:'145'
                        }
                        let width = key[item.name] ?? '180'
                        if (item.state) {
                            this.tableGroup.push({
                                label: item.name,
                                name: item.chineseName,
                                width
                            })
                        }
                        this.disposeGroup.push({
                            label: item.name,
                            name: item.chineseName,
                            state: item.state
                        })
                    })
                }
            },
            //监视复选框值变化
            handleChangeDiposeGroup(disposeGroup) {
                let configureList = []
                configureList = disposeGroup.map(i => {
                    return {
                        name: i.label,
                        chineseName: i.name,
                        state: i.state
                    }
                })
                this.getProductColumns({
                    type: 'workOrder',
                    configureList
                }).then(()=>{
                    this.$refs.tableList.updateTable()
                })
            },
            //处理排序数据
            handleSortList(sortInfoList){
                return sortInfoList.map(i => {
                    return {
                        orderBy:i.label,
                        sort:i.checkRadio
                    }
                })
            },
            //是否存储过排序条件
            isCacheSort(flag,sortInfoList){
                this.cacheSortFlag = flag
                this.sortInfoList = flag ? this.handleSortList(sortInfoList) : []
            },
            //排序
            getSortInfoList(sortInfoList){
                this.searchForm.sortInfoList = this.handleSortList(sortInfoList)
                this.$refs.tableList.getWorkOrderList(this.searchForm).then(async ()=>{
                    await setSearchCache({
                        cacheName: 'workOrder:orderBy',
                        jsonValue:JSON.stringify(sortInfoList),
                        type: 1
                    })
                })
            },
            getTotal(total){
                this.tableTotal = total
            },
            //获取勾选中表格的id
            getCheckedId(ids) {
                this.ids = ids
            },
            //点击查询获取表单数据
            getFormData(val) {
                this.searchForm.page = 1
                this.handleFormData(val)
                this.$refs.tableList.getWorkOrderList(this.searchForm)
            },
            //处理非筛选方案表单项自定义和非自定义字段数据
            handleFormData(val){
                this.searchForm.searchOther = {}
                this.customFieldMap = {}
                val.unit !== undefined && (val.unit = val.unit.toString())
                for (const key in val) {
                    /**
                     * 自定义字段表单数据放在searchOther中的customFieldMap对象中
                     * 其中计数器--日期选择器--多选框以 `[自定义字段id]:'arr[0],arr[1]'` 形式传给后端
                     * 其它类型表单项以`[自定义字段id]:'value' 形式传给后端
                     */
                    if (!isNaN(parseFloat(key)) && isFinite(key)) { 
                        let str = ''
                        if(Array.isArray(val[key])){
                            val[key].forEach(k => str += k + ',')
                            if(str.length > 0) str = str.substr(0,str.length - 1)
                        }
                        this.customFieldMap[key] = Array.isArray(val[key]) ? str : val[key]
                        this.searchForm.searchOther.customFieldMap = this.customFieldMap
                    }else{ //非自定义字段表单数据放在searchOther对象中
                        this.searchForm.searchOther[key] = val[key]
                    }
                }
                //点击查询按钮时需要将筛选方案表单项数据和非筛选方案表单项数据同时接收，做合并查询
                if(this.editableTabs.length){ 
                    const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                    this.handleSchemeData(findTab)
                }
            },
            //关闭筛选方案列表
            fromOutDrawerClose(){
                if(this.editableTabs.length){ //当没有筛选方案时不需要调用列表接口
                    const findTab = this.editableTabs.find(i => i.name == this.editableTabsValue)
                    this.schemeClick(findTab)
                }
            },
            //删除筛选方案最后一条数据时
            lastData(){
                const payload = {
                    searchOther:{
                        state:[-1]
                    },
                    page:1,
                    limit:10,
                }
                this.$refs.tableList.getWorkOrderList(payload)
            },
            //打开相对应的dialog
            openDialog(way) {
                let obj = {
                    type: 'workOrder',
                    importUrl: '/produce/work_order_import',
                    isCover:true
                }
                way == 'importMould' ? this.$refs[way].openDialog(obj) : this.$refs[way].openDialog(way)
            },
            // 导入成功
            importSuccess() {
                this.fromOutDrawerClose()
            },
            //工单批量操作
            wosHandle(type) {
                this.$refs.tableList.getWosHandle({
                    type,
                    ids: this.ids
                })
            },
            //工单加急
            wosUrgent() {
                this.$refs.tableList.getUrgent({
                    value:1,
                    ids: this.ids
                })
            },
            //获取筛选方案列表
            getList(payload){
                this.fromSavaCurrent = payload == undefined || payload.length
                this.getScreenPlanList({type:0},payload == undefined || {delIndex:payload.delIndex,name:payload.name})
            },
            //缓存state状态
            getSearchCacheFn:async function(data){
                const res = await getSearchCache(data)
                if(res.data !== null) {
                    const {searchForm} = this.formDataList
                    searchForm.state = JSON.parse(res.data)
                    this.$nextTick(()=>{
                        this.$refs.dynamicForm.getSearchCache(JSON.parse(res.data))
                    })
                    localStorage.setItem('cacheState',res.data)
                }else{
                    localStorage.removeItem('cacheState')
                }
            },
            handleTabClick(tab){
                this.searchForm.page = 1;
                this.activeValue = 'all'
                const target = this.editableTabs.find(i => i.name == tab.label)                
                this.schemeClick(target)
            },
            //获取二级分组信息
            getSecondGroupInfo(payload){
                const {typeCountData} = payload
                typeCountData.unshift({
                    optionName: "全部",
                    optionValue: "all"
                })
                this.secondGroupInfo = payload
            },
            //处理二级分组
            handleSecondGroup(group,secondGroupInfo){
                const {optionValue} = group
                const {key} = secondGroupInfo
                this.activeValue = optionValue
                this.searchForm.page = 1
                this.searchForm.secondSearchCondition = {
                    conditionName:optionValue === 'all' ? undefined : key,
                    conditionValue:optionValue === 'all' ? undefined : optionValue
                }
                this.$refs.tableList.getWorkOrderList(this.searchForm)
            },
            //筛选方案列表
            getScreenPlanList(data,p) {
                screenPlanList(data,p).then(res => {
                    if (res.code == 200) {
                        this.editableTabs = res.data.filter(i => i.isValid)
                        this.allTabs = res.data
                        if(!res.data.length) return //初始化进入页面时若无筛选方案不调用列表接口
                        /**
                         *  创建第一条筛选方案时tabs下划线默认选中，
                            当超过一条时，点击到第n个筛选方案，此时打开drawer再关闭tabs下划线默认为第n个
                         */
                        if(res.data.length && res.data.length == 1) this.editableTabsValue = res.data[0].name
                        /**
                         * 当选中第n个tabs标签页，此时打开筛选方案删除当前第n条数据时，tabs下划线默认向前移动一位
                         */
                        if(p != undefined && p.delIndex && p.name == this.editableTabsValue) {
                            this.editableTabsValue = res.data[p.delIndex - 1].name
                        }
                        /**
                         * 保存当前 || 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                         * isMounted : 筛选方案-创建筛选方案方式创建第一条筛选方案时调用列表接口
                         *             当创建第二条以上时将isMounted = '' 不需要再调用列表接口
                         */
                        if(this.fromSavaCurrent === 1 || this.isMounted == 'mounted') {
                            if (this.$store.state.tab && this.$store.state.router === this.$route.path) {
                                this.schemeClick(JSON.parse(this.$store.state.tab));
                            } else {
                                this.schemeClick(res.data[0]);
                            }                            
                        }
                    }
                })
            },
            //编辑打印模板列表
            getPrintTemplate(data) {
                this.mouldLoading = true
                printTemplate(data).then(res => {
                    if (res.code == 200) {
                        this.mouldTableData = res.data.records
                    }
                    this.mouldLoading = false
                })
            },
            //删除打印模板
            getDeleteTemplate(data) {
                deleteTemplate(data).then(res => {
                    if (res.code == 200) {
                        this.getPrintTemplate({belongModule:0})
                        this.utils.showMsg('删除成功','success')
                    }
                })
            },
            //下载模板
            getDownloadTemplate(data,templateName) {
                downloadTemplate(data,templateName).then(res => {
                    let index = templateName.indexOf('.')
                    let subName = templateName.slice(0,index)
                    this.utils.showMsg('开始下载', 'success')
                    fileDownload(res, subName + new Date().dateFormat('yyyyMMddhhmmss'),
                    'application/vnd.ms-excel;charset=UTF-8')
                })
            },
            getTemplate(way){
                this.getPrintTemplate({belongModule:0})
            },
            //上传成功
            fileSuccess() {
                this.getPrintTemplate({belongModule:0})
                this.utils.showMsg('上传成功','success')
            },
            //tabs标签页--popover框
            schemeClick(item){
                this.$store.commit('setRouter', this.$route.path);
                this.$store.commit('setTab', JSON.stringify(item));
                //默认排序条件
                const defaultSortList = [
                    {
                        orderBy:'createTime',
                        sort:'DESC'
                    },
                    {
                        orderBy:'finishProgress',
                        sort:'DESC'
                    }
                ]
                this.searchForm = { //多个筛选方案互相切换先置空
                    customFieldMap:{},
                    searchOther:{
                        state:JSON.parse(localStorage.getItem('cacheState')) ?? []
                    },
                    sortInfoList:this.cacheSortFlag ? this.sortInfoList : defaultSortList,
                    screenPlanId:item.id,
                    page:this.searchForm.page,
                    limit:10,
                }
                this.isMounted = ''
                /**
                 * getValue 这个方法单独获取已填写的非筛选方案表单项的数据
                 * 若通过selectData获取会触发'getFormData'导致每次点击筛选方案tabs标签重复调用列表接口
                 */
                let formDataPayload = this.$refs.dynamicForm.getValue()
                this.handleSchemeData(item)
                this.handleFormData(formDataPayload)
                this.$refs.tableList.getWorkOrderList(this.searchForm)
            },
            //处理筛选方案表单项自定义和非自定义字段数据
            handleSchemeData(item){
                let screenCondition = []
                let payload = {}
                screenCondition = JSON.parse(item.screenCondition).configData
                screenCondition.forEach(i => {
                    if(i.fieldId == 'unit'){
                        let str = ''
                        i.fieldValue.forEach(k =>{
                            str += k.value + ','
                        })
                        if(str.length > 0) str = str.substr(0,str.length - 1)
                        payload[i.fieldId] = str
                    }else if(i.fieldId.indexOf('Number') != -1){
                        payload[i.fieldId + 'Down'] = i.fieldValue[0]
                        payload[i.fieldId + 'Up'] = i.fieldValue[1]
                    }else if(i.fieldId.indexOf('Time') != -1){
                        payload[i.fieldId + 'Start'] = i.fieldValue[0]
                        payload[i.fieldId + 'End'] = i.fieldValue[1]
                    }else if(i.type != undefined && i.type != 'selectRadio' && i.type != 'ipt'){
                        let str = ''
                        i.fieldValue.forEach(k =>{
                            str += k + ','
                        })
                        if(str.length > 0) str = str.substr(0,str.length - 1)
                        payload[i.fieldId] = str
                    }else{
                        payload[i.fieldId] = i.fieldValue
                    }
                })
                this.editableTabsValue = item.name
                for (const key in payload) {
                    if (!isNaN(parseFloat(key)) && isFinite(key)) {
                        this.searchForm.customFieldMap[key] = payload[key]
                    }else{
                        this.searchForm[key] = payload[key]
                    }
                }
            },
            //单条数据打印
            getPrint(id) {
                this.ids = id
                this.pieceOrBatch = 'piece'
                this.getPrintTemplate({belongModule:0})
                this.$refs.print.openDialog()
            },
            //批量打印
            batchPrint(){
                this.pieceOrBatch = 'batch'
                this.getPrintTemplate({belongModule:0})
                this.$refs.print.openDialog()
            },
            //工单导出
            getWorkOrderExport() {
                let enumProps = {
                    state:{
                        0:'未开始',
                        1:'执行中',
                        2:'已结束',
                        3:'已取消'
                    }
                }
                this.$refs.tableList.getTableData(
                    this.searchForm,
                    '/produce/work_order_list',
                    '工单' + new Date().dateFormat('yyyyMMddhhmmss'),
                    0,
                    enumProps
                )
            },
            getUrl(data) {
                return request({
                    responseType: 'blob',
                    url:'/printTemplate/exportDataByModel',
                    method: 'post',
                    data
                })
            },
            getDataList(data, tit) {
                this.getUrl(data).then(res => {
                    this.utils.showMsg('开始下载', 'success')
                    fileDownload(res, tit + new Date().dateFormat('yyyyMMddhhmmss') + '.xlsx',
                        'application/vnd.ms-excel;charset=UTF-8')
                    this.excelRadio = 0
                    this.$refs.print.closeDialog()
                })
            },
            //单条-批量打印功能
            excelPrintDown() {
                let selectTemp = this.mouldTableData.find((i,index) => index == this.excelRadio)
                let payload = this.pieceOrBatch == 'piece' ? {id:selectTemp.id,workId:this.ids} : {id:selectTemp.id,workIds:this.ids}
                let index = selectTemp.templateName.indexOf('.')
                let subName = selectTemp.templateName.slice(0,index)
                this.getDataList(payload,subName)
            },
        }
    }
</script>

<style lang="less" scoped>
    .workOrder {
        overflow: auto;

        .tabHeader {
            height: 44px;
            background-color: rgb(250, 250, 250);
            padding-left: 10px;

            .el-tabs {
                float: left;
                max-width: 1000px;
            }

            /deep/ .el-tabs__header {
                margin: 0;
                padding-top: 4px;
            }

            /deep/ .el-tabs__nav-wrap::after {
                opacity: 0;
            }

            /deep/ .el-tabs__item {
                padding: 0 10px;
            }

            /deep/ .el-tabs__item:first-child {
                padding-left: 0px;
            }
            /deep/ .el-tabs__item:last-child {
                padding-right: 0px;
            }


            /deep/ .el-tabs__nav {
                height: 40px;
            }

            /deep/ .el-tabs__nav-next, /deep/ .el-tabs__nav-prev{
                line-height: 38px;
            }

            .setBtn {
                float: right;
                margin-top: 8px;
                margin-right: 20px;
            }
        }

        .formSearch {
            position: relative;
            padding: 20px 20px 0;

            .searchContent {
                border-bottom: 1px solid #e8e8e8;
                display: flex;

                .btn {
                    button:nth-child(1) {
                        margin-right: 10px;
                    }

                    button:last-child {
                        height: 28px;
                        line-height: 7px
                    }
                }
            }

            .arrow {
                position: absolute;
                left: 50%;
                bottom: -14px;
                transform: translate(-50%, -50%);
                width: 40px;
                border: 1px solid #e8e8e8;
                border-radius: 18px;
                height: 14px;
                background: #fff;
                cursor: pointer;
                text-align: center;
                line-height: 11px;
                font-size: 12px;
            }

            .isShowMore {
                height: 47px;
                overflow: hidden;
            }
        }

        /deep/ .el-drawer.rtl.card{
            .el-drawer__body{
                padding: 0;
                .operate{
                    width: 100%;
                    height: 40px;
                }
            }
        }

        .cardSet{
            flex: 1;
            overflow-y: auto;
            padding: 20px 20px 0 20px;

            .checkBox{
                padding: 18px 20px;
                border: 1px solid #e5e5e5;
                border-radius: 4px;
                max-height: 450px;
                overflow-y: auto;

                .el-checkbox-group{
                    display: flex;
                    flex-wrap: wrap;
                    .el-checkbox{
                        width: 50%;
                    }

                    .group_div {
                        display: flex;
                        height: 30px;
                        align-items: center;
                        justify-content: space-between;
                        width: 100%;

                        .key {
                            color: #02b980;
                        }
                    }

                    .iconfont.icon-row.key{
                        font-size: 12px;
                    }
                }
            }

            .el-select{
                width: 100%;
                /deep/ .el-tag.el-tag--info{
                    transition: none;
                }
                /deep/ .el-select__tags{
                    top: 3px;
                    transform: none;
                }
            }
        }

        /deep/ .el-table__empty-block {
            width: 100% !important;
        }


        /deep/ th.el-table__cell.gutter {
            background-color: #fafafa;
        }

        /deep/ .el-dialog__body {
            padding: 10px 30px 10px 30px;

            .describe {
                margin-bottom: 10px;
            }

            .mouldTableData {
                .l_mould {
                    float: left;

                    span:last-child {
                        margin-left: 8px;
                        color: rgb(153, 153, 153);
                        border: 1px solid rgb(204, 204, 204);
                        border-radius: 2px;
                        padding: 1px 3px
                    }
                }

                .r_mould {
                    float: right;
                }
            }

            .upload {
                margin-top: 20px;
            }

            .dialogBody {
                padding: 30px 50px 0;
                border: 1px solid #edeef3;
                background: #fbfbfb;

                .name,
                .el-checkbox-group {
                    float: left;
                }

                .name {
                    margin-right: 30px;
                }

                .el-checkbox-group {
                    width: 338px;

                    label.el-checkbox {
                        width: 130px;
                        margin-bottom: 10px;
                    }
                }

                .excel {
                    color: rgba(0, 0, 0, 0.85);
                    font-weight: 500v;
                }

                .el-radio-group {
                    display: flex;
                    flex-direction: column;
                    padding: 15px 0 0 10px;
                    margin-bottom: 20px;
                    justify-content: space-between;

                    .mould {
                        margin-left: 8px;
                        color: rgb(153, 153, 153);
                        border: 1px solid rgb(204, 204, 204);
                        border-radius: 2px;
                        padding: 1px 3px
                    }

                    .el-radio{
                        display: flex;
                        align-items: center;
                        margin-bottom: 10px;

                        .el-radio__label{
                            padding: 5px 0 5px 8px;
                            width: 300px;
                            overflow: hidden;
                            text-overflow: ellipsis;
                        }
                    }
                    .el-radio:last-child{
                        margin-bottom: 0;
                    }
                }

                .printDown {
                    display: inline-block;
                    width: 100%;
                    text-align: center;
                }
            }
        }
    }
</style>